<template>
    <div class="base">
        <div class="headRightItemOne hdItem">
            {{ timeInfo.nowTime }}
        </div>

        <el-row class="row-bg" justify="space-between">
            <!--登录界面-->
            <el-form :model="formData" status-icon class="login-container" ref="formRef"
                style="background-image: url('../assets/images/background.png'); background-size: 100%;">
                <h3 class="login-title">登 录</h3>
                <el-form-item label="用户名" prop="username" label-width="80px" :rules="[
                    { required: true, message: '请输入用户名' },
                ]">
                    <el-input type="input" auto-complete="off" placeholder="请输入用户名" v-model="formData.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" label-width="80px" :rules="[
                    { required: true, message: '请输入密码' },
                ]">
                    <div style="position: relative;">
                        <el-input :type="showPassword ? 'text' : 'password'" auto-complete="off" placeholder="请输入密码"
                            v-model="formData.password"></el-input>
                        <span @click="togglePasswordVisibility" class="eye-icon">
                            <img :src="showPassword ? require('@/assets/open_eye.png') : require('@/assets/close_eye.png')"
                                class="eye-icon">
                        </span>
                    </div>
                </el-form-item>

                <!-- 记住密码复选框 -->
                <el-form-item label="记住密码" label-width="80px">
                    <el-checkbox v-model="rememberMe">记住我</el-checkbox>
                </el-form-item>

                <!-- 验证码输入框 -->
                <el-form-item label="验证码" label-width="80px" prop="captcha" :rules="[
                    { required: true, message: '请输入验证码' },
                ]">
                    <el-input type="text" auto-complete="off" placeholder="请输入验证码" v-model="formData.captcha"></el-input>
                </el-form-item>
                <img v-if="captchaUrl" :src="captchaUrl" @click="refreshCaptcha" alt="验证码" class="captcha-image">
                <!-- <img src="https://localhost:44305/api/User/Captcha" @click="refreshCaptcha" alt="验证码" class="captcha-image"> -->
                <!-- <img v-if="captchaUrl !== ''" :src="captchaUrl" @click="refreshCaptcha" alt="验证码" class="captcha-image"> -->

                <div class="login-submit">
                    <el-button type="success" round style="background-color: #257B5E; letter-spacing: 5px"
                        @click="login">登录</el-button>
                    <el-button type="info" round style="letter-spacing: 5px" @click="logout">登出</el-button>
                </div>
            </el-form>
        </el-row>
        <div class="headRightItemTwo hdItem">
            {{ timeInfo.nowDate }} {{ timeInfo.nowWeek }}
        </div>
    </div>
</template>
  
<script setup>
import { reactive, ref, onMounted } from 'vue';
import router from '../router'
import { ElMessageBox } from 'element-plus';
import store from '../store/index.js';

const timeInfo = reactive({
    setInterval: null,
    nowWeek: "",
    nowDate: "",
    nowTime: "",
});

const formData = reactive({
    username: '',
    password: '',
    captcha: '', // 添加验证码字段
});

const showPassword = ref(false);

const togglePasswordVisibility = () => {
    showPassword.value = !showPassword.value;
};


const rememberMe = ref(false); // 记住密码状态
const captchaUrl = ref(''); // 验证码图片URL
const formRef = ref('')

const refreshCaptcha = async () => {
    captchaUrl.value = await generateCaptcha();
};

const generateCaptcha = async () => {
    try {
        let headersList = {
            "Accept": "*/*",
        }
        //const response = await fetch("http://localhost:5263/api/User/Captcha", {
            const response = await fetch("https://localhost:44305/api/User/Captcha", {
            method: "GET",
            headers: headersList
        });
        let data = await response.blob()
        let url = URL.createObjectURL(data)
        return url
    } catch (error) {
        console.error('Failed to fetch captcha:', error);
        return ''; // 返回空字符串或其他默认值
    }
};

const login = async () => {
    // 在登录时验证验证码的正确性
    formRef.value.validate().then(() => {
        console.log("如果验证成功，也就是必填写的值都填写了，就会执行这段函数")
        let headersList = {
            "Accept": "*/*"
        }

        //fetch(`http://localhost:5263/api/User/Login?username=${formData.username}&password=${formData.password}&code=${formData.captcha}`, {
            fetch(`https://localhost:44305/api/User/Login?username=${formData.username}&password=${formData.password}&code=${formData.captcha}`, {
            method: "POST",
            headers: headersList
        }).then(response => {
            return response.json()
        }).then(data => {
            if (data.status === "Success") {
                store.commit('setAccessToken', data.token);
                // store.commit('setAccessToken', true);
                router.push('/hello')
            } else if (data.status === "Error") {
                ElMessageBox.alert(data.msg);
                formRef.value.resetFields()
            }
        })
        formRef.value.resetFields()
    })
        .catch(error => {
            console.log("还有一些必填属性未填写")
            console.log('error', error);
        });

};

//定义获取时间的方法
function setNowTimes() {
    let myDate = new Date();
    let wk = myDate.getDay();
    let yy = String(myDate.getFullYear());
    let mm = myDate.getMonth() + 1;
    let dd = String(
        myDate.getDate() < 10 ? "0" + myDate.getDate() : myDate.getDate()
    );
    //console.log('vvvvvvvv', wk);
    let hou = String(
        myDate.getHours() < 10 ? "0" + myDate.getHours() : myDate.getHours()
    );
    let min = String(
        myDate.getMinutes() < 10
            ? "0" + myDate.getMinutes()
            : myDate.getMinutes()
    );
    let sec = String(
        myDate.getSeconds() < 10
            ? "0" + myDate.getSeconds()
            : myDate.getSeconds()
    );

    let weeks = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
    ];
    let week = weeks[wk];
    timeInfo.nowDate = yy + "-" + mm + "-" + dd + "";
    timeInfo.nowTime = hou + ":" + min + ":" + sec;
    timeInfo.nowWeek = week;
}
onMounted(() => {
    refreshCaptcha();
    timeInfo.setInterval = setInterval(() => {
        timeInfo.value = setNowTimes();
    }, 1000);
});
</script>
  
<style lang="less" scoped>
/* 添加验证码图片的样式 */
.captcha-image {
    cursor: pointer;
    margin-left: 10px;
}

//时间样式
.headRightItemOne {
    background-image: -webkit-linear-gradient(bottom, rgb(26, 45, 27), #dffce1, rgb(4, 53, 11));
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-size: 100px;
    //font-weight:bold;
    font-family: 'DS-Digital', Times, serif;
    text-align: center;
    line-height: 200px;
}

.headRightItemTwo {
    color: rgb(124, 170, 212);
    font-size: 30px;
    font-family: 'DS-Digital', Times, serif;
    text-align: right;
    position: absolute;
    bottom: 0;
    right: 10px;
}


.login-container {
    border-radius: 15px;
    background-clip: padding-box;
    margin: 0px auto 75px auto;
    width: 350px;
    padding: 35px 35px 15px 35px;
    background-color: #fff;
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #cac6c6;
    /* 添加背景样式 */
    background-image: url("../assets/background.png");
    background-size: 100%;
}

.login-title {
    margin: 0px auto 20px auto;
    text-align: center;
    color: #257B5E;
    font-weight: bold;
    font-family: "黑体", sans-serif;
    font-size: 21px;
}

.login-submit {
    display: flex;
    justify-content: center;
    margin: 10px auto 0 auto;
}

.base {

    background: url("../assets/background.png")center center no-repeat;
    //background-size: 100%;
    width: 100%;
    min-height: 100vh;
    background-size: 100% 100%;
    position: absolute;
    //解决背景平铺问题
}

.eye-icon {
    width: 20px;
    height: 15px;
    position: absolute;
    top: 50%;
    right: 14px;
    transform: translateY(-50%);
    /* 通过transform垂直居中 */
    cursor: pointer;
    /* 添加鼠标指针样式 */
    z-index: 1;
    /* 设置图标的层级，确保在密码框之上 */
}
</style>
  